<template>
  <div>
    <el-card style="margin-top: 20px">
      <el-button
        type="primary"
        icon="el-icon-plus"
        @click="addAndUpdateAttrItem()"
        style="margin-bottom: 20px"
        >添加</el-button
      >
      <div>
        <el-table :data="tradeList.records" border>
          <el-table-column
            label="序号"
            type="index"
            width="100"
          ></el-table-column>

          <el-table-column label="名称" prop="tmName"></el-table-column>

          <el-table-column label="产品logo">
            <template slot-scope="scope">
              <img :src="scope.row.logoUrl" alt="" width="100" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="300">
            <template slot-scope="{ row }">
              <el-Button
                icon="el-icon-s-tools"
                type="warning"
                @click="addAndUpdateAttrItem(row)"
                >修改</el-Button
              >
              <el-Button
                icon="el-icon-delete"
                type="danger"
                @click="deleteItem(row.id)"
                >删除</el-Button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          :total="tradeList.total"
          :current-page.sync="tradeList.current"
          :page-size.sync="tradeList.size"
          :page-sizes="[5, 10, 15]"
          :page-count="tradeList.pages"
          layout="total,  prev, pager,next,sizes,  ->,jumper"
        ></el-pagination>
      </div>
      <el-dialog
        title="添加品牌"
        :visible.sync="addFlag"
        style="width: 80%"
        class="dialog"
      >
        <el-form
          style="overflow: hidden"
          :model="dialogFormData"
          :rules="rules"
          ref="formRef"
        >
          <el-form-item
            label="产品名称"
            :inline="true"
            prop="tmName"
            for="index"
          >
            <el-input
              placeholder="请输入产品名"
              v-model="dialogFormData.tmName"
              style="width: 80%"
              id="index"
            ></el-input
          ></el-form-item>
          <el-form-item prop="logoUrl" label="品牌logo" for="index">
            <el-upload
              style="
                display: flex;
                justify-content: center;
                align-items: center;
                flex-direction: column;
                margin-right: 20%;
              "
              id="index"
              class="avatar-uploader"
              :action="`http://gmall-h5-api.atguigu.cn/admin/product/upload`"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img
                id="index"
                v-if="dialogFormData.logoUrl"
                :src="dialogFormData.logoUrl"
                class="avatar"
              />
              <i
                v-else
                class="el-icon-plus avatar-uploader-icon"
                id="index"
              ></i>
              <template #tip>
                <div>
                  <div>
                    上传的图片必须是{{ setting.uploadFileExt.join("、") }}格式
                  </div>
                  <div>小于{{ setting.uploadFileLimitSize }}kb</div>
                </div>
              </template>
            </el-upload>
          </el-form-item>
          <el-form-item style="float: right">
            <el-button @click="addTradeItem" type="primary">提交</el-button>
            <el-button @click="addFlag = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { reqTradeList, reqAddTradeItem, reqDeleteItem } from "@/api/trademark";
import { setting } from "@/mysetting";
export default {
  name: "Trademark",
  data() {
    return {
      tradeList: {
        current: 1,
        pages: 0,
        records: [],
        searchCount: true,
        size: 5,
        total: 0,
      },
      addFlag: false,
      //dialog搜集数据
      dialogFormData: {
        tmName: "",
        logoUrl: "",
      },
      setting: setting,
      rules: {
        tmName: [{ required: true, message: "不能为空", trigger: "blur" }],
        logoUrl: [
          {
            required: true,
            message: "不能为空",
            validator(rule, value, callback) {
              if (value.trim().startsWith("http")) {
                callback();
              } else {
                callback(new Error("地址不正确"));
              }
            },
          },
        ],
      },
    };
  },

  mounted() {
    this.getTradeList();
  },
  methods: {
    //获取初始数据
    async getTradeList() {
      const { current, size } = this.tradeList;
      try {
        const { data } = await reqTradeList(current, size);
        this.tradeList = data;
      } catch (e) {
        console.log(e);
      }
    },
    //添加文件开关
    addAndUpdateAttrItem(row) {
      // console.log(this.addFlag);
      if (row) {
        console.log("row", row);
        this.dialogFormData.tmName = row.tmName;
        this.dialogFormData.logoUrl = row.logoUrl;
      } else {
        this.dialogFormData.tmName = "";
        this.dialogFormData.logoUrl = "";
      }

      this.addFlag = true;
    },
    //新增请求
    async addTradeItem() {
      try {
        await reqAddTradeItem(this.dialogFormData);
        this.addFlag = false;
        this.getTradeList();
      } catch (e) {}
    },
    //提交前
    beforeAvatarUpload(file) {
      // console.log(file);
      if (!this.setting.uploadFileExt.includes(file.type.slice(6))) {
        // console.log(file);
        // this.$message({
        //   message: "格式出错",
        //   type: "error",
        // });
        this.$message.error("格式出错");
        return false;
      }
      if (file.size / 1204 > this.setting.uploadFileLimitSize) {
        this.$message.error("超载");
        return false;
      }
    },
    // 提交成功
    handleAvatarSuccess(response, file, fileList) {
      console.log("response", response, file, fileList);

      this.dialogFormData.logoUrl = response.data;
    },
    //删除
    async deleteItem(id) {
      console.log("row", id);

      await reqDeleteItem(id);
      this.$message.success("成功");
      this.getTradeList();
    },
    //清除校验
    async cancelForm() {
      // console.log(this.$refs.formRef);

      await this.$refs.formRef.clearValidate();
    },
  },
  computed: {
    // myPagination() {
    //   const { current, size } = this.tradeList;
    //   return [current, size];
    // },
  },
  watch: {
    ["tradeList.current"]: {
      handler() {
        this.getTradeList();
      },
    },
    ["tradeList.size"]: {
      handler() {
        const { current, size, total } = this.tradeList;
        if (total / size < current) {
          this.tradeList.current = Math.floor(total / size);
        }
        this.getTradeList();
      },
    },
    addFlag() {
      if (!this.addFlag) {
        const that = this;
        setTimeout(() => {
          that.cancelForm();
        });
      }
    },
  },
};
</script>
<style scoped lang="scss">
.dialog {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
